import memberApi from "@/api/member";
import globalConfig from "@/utils/config.js";
import { getFileStream } from "@/utils/http.js";

const baseUrl = globalConfig.baseUrl;

const status = {
  qyrz: {
    0: "待提交",
    10: "待审",
    11: "审核中",
    20: "审核成功",
    30: "审核驳回",
    40: "审核不通过"
  }
};

function getDate(type) {
  const date = new Date();

  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  if (type === "start") {
    year -= 60;
  } else if (type === "end") {
    year += 2;
  }
  month = month > 9 ? month : `0${month}`;
  day = day > 9 ? day : `0${day}`;

  return `${year}-${month}-${day}`;
}

const formatDecimal = (num, decimal) => {
  if (num) {
    num = num.toString();
    const index = num.indexOf(".");
    if (index !== -1) {
      num = num.substring(0, decimal + index + 2);
    } else {
      num = num.substring(0);
    }
    return parseFloat(num).toFixed(decimal);
  }
  return num;
};

function formatDayTime(val) {
  if (val) {
    const date = new Date(val.replace(/-/g, "/"));
    const Y = date.getFullYear();
    let M = date.getMonth() + 1;
    let D = date.getDate();

    if (M < 10) {
      M = `0${M}`;
    }
    if (D < 10) {
      D = `0${D}`;
    }

    return `${Y}-${M}-${D}`;
  }
  return "";
}

// 获取倒计时 天时分秒
// 取倒计时（天时分秒）
function getTimeLeft(now, start, num) {
  // 计算目标与现在时间差（毫秒）
  const time1 = new Date(start).getTime() - 1000 * num;
  const time2 = new Date(now).getTime();
  const mss = time1 - time2;
  // console.log(time1,mss)
  // 将时间差（毫秒）格式为：天时分秒
  const days = parseInt(mss / (1000 * 60 * 60 * 24));
  const hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = parseInt((mss % (1000 * 60)) / 1000);
  const dayArr = (days.toString().length <= 1 ? `0${days.toString()}` : days.toString()).split("");
  const hoursArr = (hours.toString().length <= 1 ? `0${hours.toString()}` : hours.toString()).split("");
  const minutesArr = (minutes.toString().length <= 1 ? `0${minutes.toString()}` : minutes.toString()).split("");
  const secondsArr = (seconds.toString().length <= 1 ? `0${seconds.toString()}` : seconds.toString()).split("");
  const [d1, d2, h1, h2, m1, m2, s1, s2] = [...dayArr, ...hoursArr, ...minutesArr, ...secondsArr];
  const returnData = {
    d1: Number(d1),
    d2: Number(d2),
    h1: Number(h1),
    h2: Number(h2),
    m1: Number(m1),
    m2: Number(m2),
    s1: Number(s1),
    s2: Number(s2)
  };
  return returnData;
}

// 获取倒计数
function setCountDown(currentDate, endDate, num) {
  const cDate = currentDate.replace(/-/g, "/");
  const eDate = endDate.replace(/-/g, "/");

  const padStr = (source, size, fillStr) => {
    return String(source).padStart(size, fillStr);
  };

  // 计算目标与现在时间差（毫秒）
  const time1 = new Date(eDate).getTime() - 1000 * num;
  const time2 = new Date(cDate).getTime();
  const mss = time1 - time2;
  // 将时间差（毫秒）格式为：天时分秒
  const days = padStr(parseInt(mss / (1000 * 60 * 60 * 24)), 2, 0);
  const hours = padStr(parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)), 2, 0);
  const minutes = padStr(parseInt((mss % (1000 * 60 * 60)) / (1000 * 60)), 2, 0);
  const seconds = padStr(parseInt((mss % (1000 * 60)) / 1000), 2, 0);
  if (mss <= 0) return false;
  return { days, hours, minutes, seconds };
}

/**
 * 判断是否是手机
 */
function isMobile(value) {
  return /^1[3456789][0-9]{9}$/.test(value);
}

/**
 * 判断是否是数字
 */
function isDigit(value) {
  return /^\d+$/.test(value);
}

/**
 * 判断是否是整数
 */
function isInteger(value) {
  return /^[-+]?\d+$/.test(value) && parseInt(value) >= 0;
}

/**
 * 判断是否是整数 和小数
 */
function isNumber(value) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(value);
}

/**
 * 判断是否企业认证 或者授权代表
 * type : 1 企业认证  2 是否管理员 3 是否授权代表
 */

function isInfo(tourl, type) {
  switch (type) {
    // 是否 企业认证
    case 1:
      memberApi.authorizedPersonApply().then((res1) => {
        if (res1.status == 1) {
          // 未认证
          if (res1.data.companyId > 0) {
            uni.navigateTo({
              url: tourl
            });
          } else {
            uni.showModal({
              title: "未认证",
              content: "尚未提交企业认证,企业认证通过才可继续!",
              confirmText: "去提交",
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "/pages-customer/customer/enterprise"
                  });
                }
              }
            });
          }
        } else {
          uni.showToast({
            title: res1.msg,
            icon: "none"
          });
        }
      });
      break;
    // 是否 管理员
    case 2:
      memberApi.memberInfo().then((res2) => {
        if (res2.status == 1) {
          if (res2.data.isAdmin == 1) {
            uni.navigateTo({
              url: tourl
            });
          } else {
            uni.showToast({
              title: "请用管理员账号查看",
              icon: "none"
            });
          }
        }
      });
      break;
    // 是否授权代表
    case 3:
      memberApi.authorizedPersonApply().then((res3) => {
        if (res3.status == 1) {
          if (res3.data.status == 0) {
            uni.showModal({
              title: "温馨提示",
              content: "为保障您企业在有料网平台上的权益及账户安全，请先完善授权代表信息。",
              confirmText: "去提交",
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "/pages-customer/customer/authorizedPerson"
                  });
                }
              }
            });
          } else if (res3.data.status == 20) {
            if (tourl == "/pages-member/procurement/addProcurement") {
              tourl = `${tourl}?companyId=${res3.data.companyId}&companyName=${res3.data.companyName}&phone=${res3.data.mobile}`;
            }
            uni.navigateTo({
              url: tourl
            });
          } else {
            uni.showModal({
              title: "温馨提示",
              content: "为保障您企业在有料网平台上的权益及账户安全，请先完善授权代表信息。",
              confirmText: "去提交",
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "/pages-customer/customer/enterprise"
                  });
                }
              }
            });
          }
        }
      });
      break;
    default:
      break;
  }
}

/**
 *
 * 客户是否可以下单
 */
const isSaleOrder = async (id) => {
  const res = await memberApi.checkBeforeCreateSale({ storeId: id });
  if (res.status === 1) {
    return true;
  }
  uni.showModal({
    title: "温馨提示",
    content: res.msg,
    showCancel: false
  });
  return false;
};

function clickPreview(event) {
  const getUrl = event.detail.url;
  const urlArr = getUrl.split(".");
  if (urlArr.indexOf("pdf") > 0 || urlArr.indexOf("PDF") > 0) {
    uni.showLoading({
      title: "加载中"
    });
    uni.downloadFile({
      url: getUrl,
      filePath: `${wx.env.USER_DATA_PATH}/附件`,
      header: {
        token: wx.getStorageSync("token"),
        "content-type": "application/pdf"
      },
      success(res) {
        const data = res.filePath;
        uni.openDocument({
          filePath: data,
          showMenu: true,
          fileType: "pdf",
          success(res) {
            uni.hideLoading();
          },
          fail() {
            uni.hideLoading();
            uni.showToast({
              title: "打开失败",
              icon: "none"
            });
          }
        });
      },
      fail() {
        uni.hideLoading();
        uni.showToast({
          title: "下载失败",
          icon: "none"
        });
      }
    });
  }
}

/**
 * 过滤所有特殊字符
 * */

const stripscript = function (s) {
  const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？↵\r\n]");
  let rs = "";
  for (let i = 0; i < s.length; i++) {
    rs += s.substr(i, 1).replace(pattern, "");
  }
  return rs;
};

// 根据文件流，快速打开文件
const downloadFileByFlow = async (url, params, perfix = baseUrl, { suffix = ".pdf" } = {}) => {
  const res = await getFileStream({
    url: perfix + url,
    method: "GET",
    data: params
  });
  const { data, filename } = res;
  const FileSystemManager = wx.getFileSystemManager(); // 获取全局唯一的文件管理器
  // writeFile支持处理二进制文件流 不必转base64
  FileSystemManager.writeFile({
    filePath: `${wx.env.USER_DATA_PATH}/${filename}${suffix}`,
    data,
    encoding: "binary", // 必填
    success(res) {
      wx.openDocument({
        // 打开文档
        filePath: `${wx.env.USER_DATA_PATH}/${filename}${suffix}`, // 拿上面存入的文件路径
        showMenu: true, // 显示右上角菜单
        success(res) {
          uni.hideLoading();
        }
      });
    }
  });
};

export default {
  getDate,
  formatDecimal,
  formatDayTime,
  isMobile,
  isDigit,
  isInteger,
  isNumber,
  isInfo,
  getTimeLeft,
  setCountDown,
  isSaleOrder,
  stripscript,
  downloadFileByFlow
};
